package com.wheel.autoconfigure.shiro.session;

import java.io.Serializable;
import java.util.Collection;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GlobalEnterpriseCacheSessionDAO extends EnterpriseCacheSessionDAO {

	private static Logger log = LoggerFactory.getLogger(GlobalEnterpriseCacheSessionDAO.class);

	private ShiroSessionDAO sd;

	public GlobalEnterpriseCacheSessionDAO(ShiroSessionDAO sd) {
		this.sd = sd;
	}

	@Override
	public void update(Session session) throws UnknownSessionException {
		if (session instanceof ValidatingSession && !((ValidatingSession) session).isValid()) {
			return; // 如果会话过期/停止 没必要再更新了
		}
		sd.mdfSession(session);
	}

	@Override
	public void delete(Session session) {
		sd.rmvSession(session);
	}

	@Override
	public Collection<Session> getActiveSessions() {
		return sd.qrySessions();
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable doCreate = super.doCreate(session);
		log.debug("generateSessionId:{}", doCreate);
		Serializable sessionId = sd.addSession(session);
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		log.debug("doReadSession sessionId:{}", sessionId);
		return sd.getSession(sessionId);
	}
}